﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Ext.Net;
using Ext.Net.Utilities;
using Component = Ext.Net.Component;

namespace KamLib.Controls
{
    public class PagePanel : Panel
    {
        public PageNode PageNode { get; set; }

        [DefaultValue("0px 30px 20px 30px")]
        public override string PaddingSummary
        {
            get { return ViewState.Try("PaddingSummary", "0px 30px 20px 30px"); }
            set { base.PaddingSummary = value; }
        }


        protected class ContentControl : HtmlGenericControl
        {
            private readonly PagePanel Panel;
            public ContentControl(PagePanel panel)
                : base(panel.DesignMode ? "div" : "div:body")
            {
                Panel = panel;
            }

            protected override void AddedControl(Control control, int index)
            {
                Panel.EquipContentControl(control);
                base.AddedControl(control, index);
            }
        }

        protected override HtmlGenericControl CreateContainer()
        {
            return new ContentControl(this);
        }

        public void EquipContentControl(Control uc)
        {
            var controls = new List<Control>(uc.Controls.OfType<Control>());
            uc.Controls.Clear();

            var pheader = controls.OfType<PageHeader>().FirstOrDefault();
            if (pheader == null)
                pheader = new PageHeader();
            else
                controls.Remove(pheader);

            if (pheader.Height.IsEmpty) pheader.Height = 110;

            if (PageNode != null)
            {
                if (pheader.Title.IsEmpty()) pheader.Title = PageNode.Title;
                if (pheader.IconCls.IsEmpty()) pheader.IconCls = "icon-" + PageNode.Icon + "-64s";
                if (pheader.Description.IsEmpty()) pheader.Description = PageNode.Desc;
            }

            BoxItem box2;
            var vbox = new VBoxLayout
            {
                Align = VBoxAlign.Stretch,
                BoxItems =
                {
                    new BoxItem { Items = { pheader } },
                    (box2 = new BoxItem { Flex = 1 }),
                }
            };

            box2.Items.AddRange(controls.OfType<Component>());
            uc.Controls.Add(vbox);

            controls.RemoveAll(a => a is Component);
            foreach (var control in controls)
            {
                uc.Controls.Add(control);
            }

        }
    }
}
